

import { onLogin } from "../../event"
export interface ILoginForm {
    user_name: string
    password: string
    callback?: (res: any) => void
    errorCallback?: (err: any, code: number) => void
}


enum ErrorCode {
    ErrUserNotFound = 801,
    ErrAccountDisabled = 802,
    ErrAccountLocked = 803
}

// 错误消息映射
const errorMessages: { [key: number]: string } = {
    [ErrorCode.ErrUserNotFound]: "用户名或密码错误",
    [ErrorCode.ErrAccountDisabled]: "账号已被禁用，请联系管理员",
    [ErrorCode.ErrAccountLocked]: "账号已被锁定，请稍后再试或联系管理员"
};

// 获取错误消息的函数
export function GetErrorMessage(code: number): string {
    return errorMessages[code] || `未知错误码：${code}`;
}


//用户登录处理
export function login(data: ILoginForm): Promise<any> {
    const url = '/user/login';
    return new Promise((resolve, reject) => {
        window.$theia.http
            .post(url, data)
            .then((response: any) => {
                resolve(response);
            })
            .catch((err: any) => {
                reject(err);
            });
    });
}

//监听登录事件
onLogin((data) => {
    let loginForm: ILoginForm = data as ILoginForm;
    login(loginForm).then((res) => {
        if (loginForm.callback) {
            loginForm.callback(res)
        }
    }).catch((err) => {
        if (loginForm.errorCallback) {
            let code = ((err || {}).response || {}).status || 0
            loginForm.errorCallback({ err: err, message: GetErrorMessage(code) }, code)
        }
    });

})
